#pragma once

#include <QHash>
#include <QObject>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QDebug>

#include "db_wrapper.h"
#include <functional>

template<class out_func>
inline void load_sectors(db_wrapper *db, out_func &out)
{
    QSqlQuery query = db->getQuery();
    query.prepare("SELECT "
                  "    ZN.ID AS ZONE_ID, "
                  "    ZN.NAME AS ZONE_NAME, "
                  "    ZB.ID AS BOUNDARY_ID, "
                  "    ZB.HEIGHT_MAX AS BOUNDARY_HEIGHT_MAX, "
                  "    ZB.HEIGHT_MIN AS BOUNDARY_HEIGHT_MIN, "
                  "    ZP.ID AS POINT_ID, "
                  "    parse_lat(ZP.POINT_LATITUDE) as LAT, "
                  "    parse_lon(ZP.POINT_LONGITUDE) as LON "
                  "FROM ZONE_NAME AS ZN "
                  "JOIN ZONE_BOUNDARY AS ZB ON ZB.ZONE_ID=ZN.ID "
                  "JOIN ZONE_POINTS AS ZP ON ZP.BOUNDARY_ID=ZB.ID "
                  "WHERE ZN.TYPE='SEC' ORDER BY ZN.ID, ZB.ID, ZP.ID");

    if (!query.exec())
        qWarning() << "can't exec query" + query.lastError().text();

    const auto &record = query.record();
    const int zone_id_ind = record.indexOf("ZONE_ID");

    while (query.next())
    {
        if (query.value(zone_id_ind).isNull())
            continue;

        const auto next_zone_id = query.value(zone_id_ind    ).toInt();

        out(next_zone_id, next_zone_id);
    }
}


struct worker
        : public QObject
{
    Q_OBJECT

    typedef std::function<void ()> load_func;

public:
    worker(const load_func &func, QObject *parent = nullptr);
    ~worker();

public Q_SLOTS:
    void do_work();

Q_SIGNALS:
    void finished();

private:
    load_func load_func_;
};


